package com.jsoft.model.core;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Date: 18.07.13
 * Time: 22:41
 */

public abstract class ManagerImpl<E extends BaseDao> implements Manager<E> {
    @PersistenceContext
    protected EntityManager entityManager;
    private Class<E> domainClass;

    protected ManagerImpl(Class<E> domainClass) {
        this.domainClass = domainClass;
    }

    @Override
    public E create(E entity) {
        entityManager.persist(entity);
        return entity;
    }

    @Override
    public void delete(E entity) {
        entity.setDeleted(true);
        update(entity);
    }

    @Override
    public E getById(Integer objectId) {
        return entityManager.find(domainClass, objectId);
    }

    @Override
    public E getById(Long objectId) {
        return entityManager.find(domainClass, objectId);
    }

    @Override
    public void update(E entity) {

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<E> getAllList() {
        return (List<E>) entityManager.createQuery("select e from " + domainClass.getName() + " e").getResultList();
    }

    @Override
    public EntityManager getEntityManager() {
        return entityManager;
    }

    @Override
    public List<E> getByIds(Integer... ids) {
        StringBuilder idsStr = new StringBuilder();
        String comma = "";
        for (Integer id : ids) {
            idsStr.append(comma).append(id);
            comma = ",";
        }
        return entityManager.createQuery("select e from " + domainClass.getName() + " e where e.objectId in (" + idsStr.toString() + ")", domainClass).getResultList();
    }
}